﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Cricket.LinqModel;
using Cricket.LinqData;

public partial class SessionReport : System.Web.UI.Page
{
    #region Variable Declaration
    IDataRepository _dataObject = new DataRepository();
    MatchSchedule matchSchedule;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HttpCookie cookie = Request.Cookies["Admin"];
            if (cookie == null)
                Response.Redirect("Login.aspx");
            else
                bindMatch();
        }
    }
    private void bindMatch()
    {
        matchSchedule = new MatchSchedule(_dataObject);
        List<GetMatchesForReportResult> lstResult = new List<GetMatchesForReportResult>();
        lstResult = matchSchedule.GetMatchesForReport();
        if (lstResult.Count > 0)
        {
            drpMatch.DataSource = lstResult;
            drpMatch.DataTextField = "Teams";
            drpMatch.DataValueField = "Id";
            drpMatch.DataBind();
            drpMatch.Items.Insert(0, new ListItem("Select Match", "0"));
        }
    }
    private static DataTable GetData(string query)
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        return dt;
                    }
                }
            }
        }
    }
    protected void Show_Hide_OrdersGrid(object sender, EventArgs e)
    {
        ImageButton imgShowHide = (sender as ImageButton);
        GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
        if (imgShowHide.CommandArgument == "Show")
        {
            row.FindControl("pnlOrders").Visible = true;
            imgShowHide.CommandArgument = "Hide";
            imgShowHide.ImageUrl = "~/images/minus.png";
            string bookieId = grdBookie.DataKeys[row.RowIndex].Value.ToString();
            GridView grdCustomers = row.FindControl("grdCustomers") as GridView;
            BindBookieCustomers(bookieId, grdCustomers);
        }
        else
        {
            row.FindControl("pnlOrders").Visible = false;
            imgShowHide.CommandArgument = "Show";
            imgShowHide.ImageUrl = "~/images/plus.png";
        }
    }
    private void BindBookieCustomers(string bookieId, GridView grdCustomers)
    {
        grdCustomers.ToolTip = bookieId;
        grdCustomers.DataSource = GetData(string.Format("SELECT DISTINCT C.Id AS CustomerId, C.Username AS CustomerName, SUM(BettingAmount) AS BettingAmount from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId WHERE C.AdminId = '{0}' AND CB.MatchSchduleId = " + drpMatch.SelectedValue + "  AND B.BettingTypeId = 1 GROUP BY C.Username,C.Id ORDER BY C.Username asc", bookieId));
        grdCustomers.DataBind();
    }
    protected void OnOrdersGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView grdCustomers = (sender as GridView);
        grdCustomers.PageIndex = e.NewPageIndex;
        BindBookieCustomers(grdCustomers.ToolTip, grdCustomers);
    }
    protected void Show_Hide_ProductsGrid(object sender, EventArgs e)
    {
        ImageButton imgShowHide = (sender as ImageButton);
        GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
        if (imgShowHide.CommandArgument == "Show")
        {
            row.FindControl("pnlProducts").Visible = true;
            imgShowHide.CommandArgument = "Hide";
            imgShowHide.ImageUrl = "~/images/minus.png";
            int customerId = Convert.ToInt32((row.NamingContainer as GridView).DataKeys[row.RowIndex].Value);
            GridView grdAllCustomers = row.FindControl("grdAllCustomers") as GridView;
            BindAllCustomers(customerId, grdAllCustomers);
        }
        else
        {
            row.FindControl("pnlProducts").Visible = false;
            imgShowHide.CommandArgument = "Show";
            imgShowHide.ImageUrl = "~/images/plus.png";
        }
    }
    private void BindAllCustomers(int customerId, GridView grdAllCustomers)
    {
        grdAllCustomers.ToolTip = customerId.ToString();
        grdAllCustomers.DataSource = GetData(string.Format("SELECT B.[Over], MSR.Runs as ActualRun, CASE CB.BetFor WHEN 'L' THEN B.LagadiRate ELSE B.KhadhiRate END AS Runs, CB.Rate,CB.BetFor AS BettingFor,BettingAmount AS BettingAmount,CONVERT(varchar(20),DATEADD(MI,30,DATEADD(hh,5,CB.CreatedDate)),113) As Date from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN MatchSessionResult MSR ON B.[Over] = MSR.[Over] AND B.[TeamId] = MSR.[TeamId] WHERE C.Id = '{0}' AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND MSR.MatchScheduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 1 ", customerId));
        grdAllCustomers.DataBind();
    }
    protected void OnProductsGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView grdAllCustomers = (sender as GridView);
        grdAllCustomers.PageIndex = e.NewPageIndex;
        BindAllCustomers(int.Parse(grdAllCustomers.ToolTip), grdAllCustomers);
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["Admin"];
        if (cookie == null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {
            DataTable dt = new DataTable();
            Admin admin = new Admin(_dataObject);
            List<AdminResult> adminResult = new List<AdminResult>();
            adminResult = admin.GetAdminDetailsById(Convert.ToInt32(cookie["AdminId"]));
            if (adminResult[0].CommonRate == 2)
            {
                //dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, (SUM(CB.BettingAmount) * -1) AS BettingAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 1 AND A.Id IN (Select Cl.AdminId From Client Cl) GROUP BY A.Id, A.FirstName, A.LastName");
                dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, (SUM(CB.BettingAmount) * -1) AS BettingAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 1  GROUP BY A.Id, A.FirstName, A.LastName");
            }
            else
            {
                dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, (SUM(CB.BettingAmount) * -1) AS BettingAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 1  GROUP BY A.Id, A.FirstName, A.LastName");
                //dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, (SUM(CB.BettingAmount) * -1) AS BettingAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE B.AdminId = 3 AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 1 GROUP BY A.Id, A.FirstName, A.LastName");
            }

            if (dt != null && dt.Rows.Count > 0)
            {
                layerError.Attributes.Add("style", "display:none;");
                layerError.InnerHtml = "";
                grdBookie.DataSource = dt;
                grdBookie.DataBind();
            }
            else
            {
                grdBookie.DataSource = null;
                grdBookie.DataBind();
                layerError.Attributes.Add("style", "display:block;");
                layerError.InnerHtml = "No results declared yet!";
            }
        }
    }
}